import {reactive, ref, toRefs, getCurrentInstance, watch, computed} from "vue"

export default function () {
    const {proxy} = getCurrentInstance()

    const totalNums = ref(0)
    const page = ref(1)
    const pageSize = ref(20) // 每页显示几条
    const pageSizeNum = ref([20, 30, 40]) //调整每页显示条数

    const ascended = ref(false) //排序方式
    const sortFieldName = ref('created') //排序属性名

    const apiPath = ref('')

    const searchParams = reactive({})
    const searchBtnLoading = ref(false)

    let result = reactive({
        list: []
    })
    const selectedIds = ref([])
    const loading = ref(false)

    const dialogShow = ref(false)
    const dialogForm = reactive({})
    const dialogFormRef = ref(null)
    const dialogParams = reactive({
        type: '',// add:创建  edit：编辑
        loading: false,
        data:{}, //提交的其他参数，不在表单编辑内
        row:{},//触发的行数据
    })

    const handleAdd = (data,row) => {
        dialogShow.value = true
        dialogParams.type = 'add'
        dialogParams.data = data || {}
        dialogParams.row = row || {}
        resetDialogForm(dialogFormRef.value)
    }
    const handleEdit = (row,data) => {
        dialogShow.value = true
        dialogParams.type = 'edit'
        dialogParams.data = data
        dialogParams.row = row || {}
        setTimeout(() => {
            for (let key in dialogForm) {
                dialogForm[key] = row[key]
            }
        }, 50)
    }
    const resetDialogForm = (formEl) => {
        if (!formEl) return
        // console.log(formEl);
        formEl.resetFields()
    }
    const submitDialogForm = (formEl,params,callback) => {
        if (!formEl) return
        formEl.validate((valid, fields) => {
            if (valid) {
                dialogParams.loading = true
                let data;
                if(params){
                    data = params
                }else{
                    data = dialogForm
                }
                let url = apiPath.value;
                data = {
                    ...data,
                    ...dialogParams.data
                }
                if (dialogParams.type == 'edit') {
                    url += `/${data.sid}`
                    delete data.sid
                }
                let method = 'post';
                if(dialogParams.type == 'edit'){
                    method = 'put'
                }

                proxy.$axios[method](url, data)
                    .then((res) => {
                        dialogParams.loading = false
                        if (res.data.code == 200) {
                            closeDialog()
                            proxy.$message({
                                message: `${dialogParams.type == 'add' ? "添加成功！" : "编辑成功！"}`,
                                type: "success"
                            })
                            if(callback && typeof callback === 'function'){
                                callback()
                            }else{
                                getData()
                            }
                        } else {
                            proxy.$message({
                                message: res.data.msg,
                                type: "error"
                            })
                        }
                    })
                    .catch((err) => {
                        dialogParams.loading = false
                    })
            }
        })
    }
    const closeDialog = () => {
        dialogShow.value = false
        resetDialogForm(dialogFormRef.value)
    }

    const handleAction = (method,url,data,callback) => {
        let params = {};
        if(data){
            if(method === 'get'){
                params.params = data
            }else{
                params.data = data
            }
        }
        proxy.$axios[method](url, {...params})
            .then((res) => {
                if (res.data.code === 200) {
                    proxy.$message({
                        message: "操作成功",
                        type: "success"
                    })
                    if(callback && typeof callback === 'function'){
                        callback()
                    }else{
                        getData()
                    }
                } else {
                    proxy.$message({
                        message: res.data.msg,
                        type: "error"
                    })
                }
            })
            .catch((err) => {
            })
    }

    const handleDelete = (ids,callback) =>{
        if(!ids){
            return;
        }
        let sidList = [];
        if(typeof ids == 'string'){
            sidList = [ids]
        }else{
            sidList = ids
        }
        proxy.$axios.put(apiPath.value+'/delete', {sidList:sidList})
            .then((res) => {
                if (res.data.code == 200) {
                    proxy.$message({
                        message: "操作成功",
                        type: "success"
                    })
                    if(callback && typeof callback === 'function'){
                        callback()
                    }else{
                        getData()
                    }
                } else {
                    proxy.$message({
                        message: res.data.msg,
                        type: "error"
                    })
                }
            })
            .catch((err) => {
            })
    }

    function handleAllSelected(d) {
        selectedIds.value = d.map(v=>v.sid)
    }
    function handleSelected(d){
        selectedIds.value = d.map(v=>v.sid)
    }

    const handleSearch = async () => {
        searchBtnLoading.value = true
        await getData();
        searchBtnLoading.value = false
    }

    const getData = async () => {
        let params = {
            current: page.value,
            size: pageSize.value,
            ascended:ascended.value,
            sortFieldName:sortFieldName.value,
            ...searchParams
        }
        for (let key in params){
            if((params[key]+'').trim() === ''){
                delete params[key]
            }
        }
        loading.value = true;
        // console.log('getData', apiPath.value);
        await proxy.$axios
            .get(apiPath.value, {params: params})
            .then((res) => {
                // console.log(res);
                switch (res.data.code) {
                    case 200:
                        let resData = res.data.data
                        result.list = resData.records
                        totalNums.value = Number(resData.total)
                        break
                    default:
                        proxy.$message({message: res.data.msg, type: "error"})
                        break
                }
                loading.value = false;
            })
            .catch((error) => {
                loading.value = false;
            })
    }

    // 切换每页显示条数
    watch(pageSize, async (val) => {
        page.value = 1
        await getData()
    })
    // 跳转第几页
    watch(page, async (val) => {
        await getData()
    })

    const importData = (url,searchParams) => {
        proxy.$axios
            .get(url, {
                responseType: "blob",
                params:searchParams
            })
            .then((res) => {
                if (res.status === 200) {
                    proxy.$message({ message: "导出成功,请在浏览器下载列表查看", type: "success" });

                    // 获取 Content-Disposition 头部
                    const contentDisposition = res.headers["content-disposition"];
                    let fileName = "download"; // 默认文件名

                    if (contentDisposition && contentDisposition.indexOf("attachment") !== -1) {
                        // 使用正则匹配 filename* 部分
                        const match = contentDisposition.match(/filename\*=([^;]+)/);
                        if (match && match[1]) {
                            // 解码并提取文件名
                            const encodedFileName = match[1].split("''")[1]; // 去掉 utf-8'' 部分
                            fileName = decodeURIComponent(encodedFileName); // 解码 URL 编码的文件名
                        } else {
                            // 如果没有找到 filename*，可以尝试获取 filename
                            const filenameMatch = contentDisposition.match(/filename="([^"]+)"/);
                            if (filenameMatch && filenameMatch[1]) {
                                fileName = filenameMatch[1];
                            }
                        }
                    }

                    // 创建 Blob 对象
                    let blob = new Blob([res.data], { type: res.headers["content-type"] });
                    let href = window.URL.createObjectURL(blob);

                    // 创建链接元素
                    const link = document.createElement('a');
                    link.href = href;
                    link.download = fileName; // 使用提取的文件名

                    document.body.appendChild(link);
                    link.click();

                    // 清理临时 URL 和链接元素
                    URL.revokeObjectURL(href);
                    link.remove();
                } else {
                    if (res.data.code !== 403) {
                        proxy.$message({ message: res.data.msg, type: "error" });
                    }
                }
            })
            .catch((err) => {
                // 处理错误
                console.error("请求失败", err);
            });
    };

    return {
        page,
        pageSize,
        pageSizeNum,
        totalNums,
        ascended,
        sortFieldName,
        searchParams,
        searchBtnLoading,
        apiPath,
        handleSearch,
        getData,
        loading, ...toRefs(result),
        dialogFormRef,
        dialogShow,
        handleAdd,
        handleEdit,
        resetDialogForm,
        handleAllSelected,
        handleSelected,
        selectedIds,
        dialogForm,
        submitDialogForm,
        dialogParams,
        closeDialog,
        handleAction,
        importData,
        handleDelete
    }
}
